package Code.Day8_20240925.com.dx.day08.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.*;

/**
 * @ClassName BaseDao
 * @Description 数据库操作工具类
 * @Author 12994
 * @Date 2024/9/25 10:52
 * @Version 1.0
 **/
public class BaseDao {
    public Connection connection;
    public PreparedStatement ps;
    public ResultSet rs;

    protected static Logger logger = LoggerFactory.getLogger(BaseDao.class);

    public Connection getConn() {
        String driver = "com.mysql.cj.jdbc.Driver";
        String url = "jdbc:mysql://localhost:3306/myschool_db";
        String user = "root";
        String pwd = "root";
        try {
//            Class.forName(driver);
            return DriverManager.getConnection(url, user, pwd);
        } catch (SQLException e) {
            logger.warn(String.valueOf(e.fillInStackTrace()));
            return null;
        }
    }

    /**
     * 基本增删改方法封装
     *
     * @param sql     需要执行的, 含有占位符的sql语句
     * @param objList 可变参数, 按照占位符顺序提供
     * @return 操作成功影响的行数
     */
    public int baseUpdate(String sql, Object... objList) {
        try {
            if (this.connection == null) {
                this.connection = this.getConn();
            }
            this.ps = this.connection.prepareStatement(sql);
            for (int i = 0; i < objList.length; i++) {
                this.ps.setObject(i + 1, objList[i]);
            }
            return this.ps.executeUpdate();
        } catch (SQLException e) {
            logger.warn(String.valueOf(e.fillInStackTrace()));
        }
        return -1;
    }

    public ResultSet baseQuery(String sql) {
        try {
            if (this.connection == null) {
                this.connection = this.getConn();
            }
            this.ps = this.connection.prepareStatement(sql);
            return this.ps.executeQuery();
        } catch (SQLException e) {
            logger.warn(String.valueOf(e.fillInStackTrace()));
            return null;
        }
    }
}
